<?php 
	require("../wp-blog-header.php");
	require("event-config.php");

	if(!isset($_GET['p']) || !isset($_POST['phone_number']) || !isset($_POST['user_email']) || !isset($_POST['user_facebook'])
		|| !isset($_POST['first_name']) || !isset($_POST['last_name']))
	{
		header("Location: error.php");
	}
	else
	{
		$event_id 		= $_GET['p'];
		$phone_number 	= $_POST['phone_number'];
		$first_name 	= $_POST['first_name'];
		$last_name 		= $_POST['last_name'];
		$user_email 	= $_POST['user_email'];
		$user_facebook 	= $_POST['user_facebook'];

		$regex = '/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
		if ($first_name == "" || $last_name == "") {
			header("Location: " . $_SERVER['HTTP_REFERER']. "&error=0#reg-error");
		}
		elseif (!eregi("[0-9][0-9][0-9][0-9][0-9][0-9][0-9]+", $phone_number)) {
			header("Location: " . $_SERVER['HTTP_REFERER']. "&error=1#reg-error");
		}
		elseif(!preg_match($regex, $user_email)) {
			header("Location: " . $_SERVER['HTTP_REFERER']. "&error=2#reg-error");
		} else {
			//update firstname & lastname
			$user_id = wp_get_current_user()->ID;
			wp_update_user( array ( 'ID' => $user_id, 'first_name' => $first_name, 'last_name' => $last_name ) ) ;

			//register and update phone number
			$user_login = wp_get_current_user()->user_login;
			$query1 = "INSERT INTO $EVENT_JOIN(`event_id`, `user_login`) VALUES ('$event_id', '$user_login')";
			$query2 = "UPDATE `wp_users` 
					   SET `phone_number`= '$phone_number', `user_email`= '$user_email', `user_facebook`= '$user_facebook' 
					   WHERE `user_login` = '$user_login'";

			//run query
			if(execute($query1) && execute($query2))
			{
				//get the poll answer
				if (isset($_POST['answer'])) {
					$answer = $_POST['answer'];
					$query3 = "INSERT INTO `event_poll_result` (`user_login`, `answer_id`) VALUES ";
					if (is_array($answer)) {
						# checkbox
						$c = count($answer);
						for ($i=0; $i < $c; $i++) { 
							$query3 .= "('$user_login', '$answer[$i]')";
							if ($i < $c - 1) {
								$query3 .= ",";
							}
						}
					} else {
						$query3 .= "('$user_login', '$answer')";
					}
					execute($query3);
				}

				header("Location: event.php?p=$event_id");
			}
			else
			{
				header("Location: error.php");
			}
		}
	}
 ?>